
package com.ruoyi.backend.config;

import io.minio.*;
import io.minio.errors.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Data
@Configuration
public class MinioConfig {
    @Value("${minio.endpoint}")
    private String endPoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.backupBucket}")
    private String backupBucket;

    // 新增 inversion 桶名称
    @Value("${minio.inversionBucket:inversion}")
    private String inversionBucket;

    // 新增 satellite 桶名称
    @Value("${minio.satelliteBucket:satellite}")
    private String satelliteBucket;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endPoint)
                .credentials(accessKey, secretKey)
                .build();
    }

    /**
     * 应用启动后执行，用于创建所需的bucket并设置访问权限
     */
    @PostConstruct
    public void initBuckets() throws ServerException, InsufficientDataException, ErrorResponseException,
            IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException,
            XmlParserException, InternalException {

        MinioClient client = minioClient();

        // 创建 inversion 桶
        createPublicBucket(client, inversionBucket);

        // 创建 satellite 桶
        createPublicBucket(client, satelliteBucket);
    }

    /**
     * 创建具有公开读取权限的桶
     *
     * @param client Minio客户端
     * @param bucketName 桶名称
     */
    private void createPublicBucket(MinioClient client, String bucketName) throws ServerException,
            InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException,
            InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        // 判断桶是否存在
        boolean exists = client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!exists) {
            // 创建桶
            client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }

        // 设置桶策略为公开读取
        String policy = "{\n" +
                "  \"Version\": \"2012-10-17\",\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Effect\": \"Allow\",\n" +
                "      \"Principal\": {\"AWS\": [\"*\"]},\n" +
                "      \"Action\": [\"s3:GetBucketLocation\",\"s3:ListBucket\"],\n" +
                "      \"Resource\": [\"arn:aws:s3:::" + bucketName + "\" ]\n" +
                "    },\n" +
                "    {\n" +
                "      \"Effect\": \"Allow\",\n" +
                "      \"Principal\": {\"AWS\": [\"*\"]},\n" +
                "      \"Action\": [\"s3:GetObject\"],\n" +
                "      \"Resource\": [\"arn:aws:s3:::" + bucketName + "/*\" ]\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        client.setBucketPolicy(SetBucketPolicyArgs.builder()
                .bucket(bucketName)
                .config(policy)
                .build());
    }
}


